const Article = require("../mongoose/article");
const { articleAddVerify } = require("../verifyParams/article");

//查找所有的article
exports.articleAll = async (ctx) => {
  try {
    let res = await Article.find();
    console.log(res);
    if (!res.length) throw new Error("服务器错误");
    console.log(res);
    ctx.body = {
      status: 200,
      msg: "查找数据成功",
      data: res,
    };
  } catch (error) {
    ctx.body = {
      status: 100,
      msg: error.message,
    };
  }
};

//添加article
exports.articleAdd = async (ctx) => {
  ctx.verifyParams(articleAddVerify);
  try {
    let res = await Article.create(ctx.request.body);
    console.log(res);
    if (![res].length) throw new Error("服务器错误");
    ctx.body = {
      status: 200,
      msg: "添加数据成功",
      data: res,
    };
  } catch (error) {
    ctx.body = {
      status: 100,
      msg: error.message,
    };
  }
};

exports.articleOne = async (ctx) => {
  let id = ctx.params.id;
  try {
    // let res = await Article.findOne({ author: "罗贯中" });
    let res = await Article.findById({ _id: id });
    console.log(res);
    if (![res].length) throw new Error("服务器错误");
    ctx.body = {
      status: 200,
      msg: "查找数据成功",
      data: res,
    };
  } catch (error) {
    ctx.body = {
      status: 100,
      msg: error.message,
    };
  }
};

exports.articleDel = async (ctx) => {
  let id = ctx.params.id;
  try {
    // let res = await Article.deleteOne({ author: "东野圭吾" });
    let res = await Article.findByIdAndDelete({ _id: id });
    console.log(res);
    if (![res].length) throw new Error("服务器错误");
    ctx.body = {
      status: 200,
      msg: "删除数据成功",
      data: res,
    };
  } catch (error) {
    ctx.body = {
      status: 100,
      msg: error.message,
    };
  }
};

exports.articleUpdateOne = async (ctx) => {
  let { id } = ctx.request.body;

  try {
    let res = await Article.findByIdAndUpdate({ _id: id }, {});
    console.log(res);
    if (![res].length) throw new Error("服务器错误");
    ctx.body = {
      status: 200,
      msg: "修改数据成功",
      data: res,
    };
  } catch (error) {
    ctx.body = {
      status: 100,
      msg: error.message,
    };
  }
};

/* exports.articleAdd = (ctx) => {
  Article.create(
    { title: "白夜行", author: "东野圭吾", des: "杀人犯的自我修养" },
    { title: "三国", author: "罗贯中", des: "乱世英雄" }
  )
    .then((res) => {
      console.log(res);
    })
    .catch((err) => {
      console.log(err);
    });

  ctx.body = {
    msg: "add",
  };
}; */
